// 用户相关功能

// 确保updateNavigation在全局作用域中可用
if (!window.updateNavigation) {
    window.updateNavigation = function() {
        const userInfoLink = document.getElementById('userInfoLink');
        const loginLink = document.getElementById('loginLink');
        const registerLink = document.getElementById('registerLink');
        const logoutLink = document.getElementById('logoutLink');
        
        // 检查是否有登录信息
        const savedUserId = localStorage.getItem('userId');
        if (savedUserId) {
            window.currentUserId = savedUserId;
            userInfoLink.style.display = 'block';
            logoutLink.style.display = 'block';
            loginLink.style.display = 'none';
            registerLink.style.display = 'none';
        } else {
            window.currentUserId = null;
            userInfoLink.style.display = 'none';
            logoutLink.style.display = 'none';
            loginLink.style.display = 'block';
            registerLink.style.display = 'block';
        }
    };
}

// 显示登录模态框
window.showLoginModal = function() {
    loginModal.style.display = 'block';
};

// 关闭登录模态框
window.closeLoginModal = function() {
    loginModal.style.display = 'none';
    // 清空表单
    document.getElementById('loginForm').reset();
    document.getElementById('loginMessage').style.display = 'none';
};

// 用户登录
window.login = function() {
    const username = document.getElementById('loginUsername').value;
    const password = document.getElementById('loginPassword').value;
    
    if (!username || !password) {
        if (window.showMessage) {
            window.showMessage('loginMessage', '请输入用户名和密码', false);
        }
        return;
    }
    
    // 发送登录请求
    fetch('/knowledge-qa/api/user/login', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({username, password})
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 保存用户信息到localStorage
            localStorage.setItem('userId', data.user.id);
            localStorage.setItem('username', data.user.username);
            
            // 更新导航
            window.updateNavigation();
            
            // 关闭模态框并显示成功消息
            if (window.closeLoginModal) {
                window.closeLoginModal();
            }
            alert('登录成功！');
        } else {
            if (window.showMessage) {
                window.showMessage('loginMessage', data.message || '登录失败', false);
            }
        }
    })
    .catch(error => {
        console.error('登录失败:', error);
        if (window.showMessage) {
            window.showMessage('loginMessage', '登录失败，请稍后重试', false);
        }
    });
};

// 显示注册模态框
window.showRegisterModal = function() {
    registerModal.style.display = 'block';
};

// 关闭注册模态框
window.closeRegisterModal = function() {
    registerModal.style.display = 'none';
    // 清空表单
    document.getElementById('registerForm').reset();
    document.getElementById('registerMessage').style.display = 'none';
};

// 用户注册
window.register = function() {
    const username = document.getElementById('registerUsername').value;
    const password = document.getElementById('registerPassword').value;
    const phone = document.getElementById('registerPhone').value;
    const email = document.getElementById('registerEmail').value;
    
    if (!username || !password) {
        window.showMessage('registerMessage', '用户名和密码不能为空', false);
        return;
    }
    
    // 发送注册请求
    fetch('/knowledge-qa/api/user/register', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({username, password, phone, email})
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 关闭模态框并显示成功消息
            window.closeRegisterModal();
            alert('注册成功！请登录');
        } else {
            window.showMessage('registerMessage', data.message || '注册失败', false);
        }
    })
    .catch(error => {
        console.error('注册失败:', error);
        if (window.showMessage) {
            window.showMessage('registerMessage', '注册失败，请稍后重试', false);
        }
    });
};

// 用户登出（仅退出登录，不删除账号）
window.logout = function() {
    if (confirm('确定要退出登录吗？')) {
        // 只执行普通的退出登录操作
        // 清除localStorage中的用户信息
        localStorage.removeItem('userId');
        localStorage.removeItem('username');
        
        // 更新导航
        window.currentUserId = null;
        window.updateNavigation();
        
        // 跳转到首页
        if (window.showHome) {
            window.showHome();
        }
        
        alert('退出登录成功！');
    }
};

// 用户注销账号（删除数据库中的账号和相关信息）
window.deleteAccount = function() {
    if (confirm('确定要注销账号吗？注销后将删除您的所有信息和头像，此操作不可恢复。')) {
        // 获取当前用户ID，可以从window或localStorage中获取
        let userId = window.currentUserId;
        
        // 如果window中没有用户ID，尝试从localStorage中获取
        if (!userId) {
            userId = localStorage.getItem('userId');
        }
        
        // 检查用户ID是否存在且有效
        if (!userId || isNaN(userId)) {
            alert('无法获取用户信息，请重新登录后再试。');
            return;
        }
        
        // 调用后端API删除用户
        fetch(`/knowledge-qa/api/user/${userId}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            // 清除localStorage中的用户信息
            localStorage.removeItem('userId');
            localStorage.removeItem('username');
            
            // 更新导航
            window.currentUserId = null;
            window.updateNavigation();
            
            // 跳转到首页
            if (window.showHome) {
                window.showHome();
            }
            
            alert(data.message || '账号注销成功！');
        })
        .catch(error => {
            console.error('注销失败:', error);
            alert('注销失败，请稍后重试');
        });
        }
    }


// 加载用户信息
function loadUserInfo() {
    if (!currentUserId) return;
    
    fetch(`/knowledge-qa/api/user/info/${currentUserId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success && data.user) {
                const user = data.user;
                const avatarElement = document.getElementById('userAvatar');
                
                // 检查是否已有img元素
                const existingImg = avatarElement.querySelector('img');
                
                // 如果有头像URL
                if (user.avatar) {
                    if (existingImg) {
                        // 更新已有img元素的src
                        existingImg.src = user.avatar;
                    } else {
                        // 保留原有内容（包括上传提示和隐藏input），在内部添加img元素
                        const originalContent = avatarElement.innerHTML;
                        avatarElement.innerHTML = originalContent + `<img src="${user.avatar}" alt="用户头像" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; border-radius: 50%;">`;
                    }
                } else {
                    // 没有头像URL，显示文字
                    // 保留上传提示和隐藏input
                    const uploadTip = avatarElement.querySelector('.avatar-upload-tip');
                    const uploadInput = avatarElement.querySelector('#avatarUploadInput');
                    
                    avatarElement.innerHTML = '';
                    avatarElement.textContent = user.nickname ? user.nickname.substring(0, 2) : '用户';
                    
                    if (uploadTip) {
                        avatarElement.appendChild(uploadTip);
                    }
                    if (uploadInput) {
                        avatarElement.appendChild(uploadInput);
                    }
                }
                
                document.getElementById('userNickname').textContent = user.nickname || user.username;
                document.getElementById('userIntroduction').textContent = user.introduction || '这个人很懒，什么都没有留下';
                document.getElementById('userCoinBalance').textContent = user.coinBalance || 0;
            }
        })
        .catch(error => {
            console.error('加载用户信息失败:', error);
        });
}

// 显示充值模态框
window.showRechargeModal = function() {
    if (!currentUserId) {
        alert('请先登录');
        return;
    }
    rechargeModal.style.display = 'block';
}

// 关闭充值模态框
window.closeRechargeModal = function() {
    rechargeModal.style.display = 'none';
    // 清空表单
    document.getElementById('rechargeForm').reset();
    document.getElementById('rechargeMessage').style.display = 'none';
}

// 金币充值
window.recharge = function() {
    const amount = document.getElementById('rechargeAmount').value;
    
    if (!amount || isNaN(amount) || amount <= 0) {
        if (window.showMessage) {
            window.showMessage('rechargeMessage', '请输入有效的充值金额', false);
        }
        return;
    }
    
    // 跳转到虚拟支付页面
    const userId = window.currentUserId;
    const rechargeAmount = parseInt(amount);
    
    // 关闭当前充值模态框
    if (window.closeRechargeModal) {
        window.closeRechargeModal();
    }
    
    // 打开虚拟支付页面
    const paymentUrl = `/knowledge-qa/static/pages/virtual_payment.html?userId=${userId}&amount=${rechargeAmount}`;
    
    // 在新窗口中打开支付页面
    window.open(paymentUrl, '_blank', 'width=600,height=600,top=100,left=100,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no');
}

// 显示金币交易记录
window.showCoinTransactions = function() {
    if (!currentUserId) {
        alert('请先登录');
        return;
    }
    
    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.style.display = 'block';
    
    const modalContent = document.createElement('div');
    modalContent.className = 'modal-content';
    modalContent.innerHTML = `
        <span class="close" onclick="closeTransactionsModal()">&times;</span>
        <h2>金币交易记录</h2>
        <div style="margin-bottom: 1rem;">
            <button id="btnAllTransactions" class="btn" onclick="loadTransactions('all')">全部记录</button>
            <button id="btnRechargeRecords" class="btn" onclick="loadTransactions('recharge')">充值记录</button>
            <button id="btnConsumeRecords" class="btn" onclick="loadTransactions('consume')">消费记录</button>
        </div>
        <div id="transactionsContainer" style="max-height: 400px; overflow-y: auto;">
            <p style="text-align:center; color:#999;">加载中...</p>
        </div>
    `;
    
    modal.appendChild(modalContent);
    modal.id = 'transactionsModal';
    document.body.appendChild(modal);
    
    // 加载全部交易记录
    loadTransactions('all');
}

// 关闭交易记录模态框
window.closeTransactionsModal = function() {
    const transactionsModal = document.getElementById('transactionsModal');
    if (transactionsModal) {
        // 从DOM中完全移除模态框，而不仅仅是隐藏
        transactionsModal.remove();
    }
}

// 显示头像上传模态框
window.showAvatarUploadModal = function() {
    if (!currentUserId) {
        alert('请先登录');
        return;
    }
    
    const avatarInput = document.getElementById('avatarUploadInput');
    if (avatarInput) {
        avatarInput.click();
        avatarInput.onchange = function(e) {
            handleAvatarUpload(e.target.files[0]);
        };
    }
};

// 处理头像上传
function handleAvatarUpload(file) {
    if (!file) return;
    
    // 创建一个FileReader来读取图片文件并转换为base64
    const reader = new FileReader();
    reader.onload = function(event) {
        const base64Image = event.target.result;
        
        // 发送头像更新请求
        fetch('/knowledge-qa/api/user/avatar', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                userId: currentUserId,
                avatar: base64Image
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 更新成功，重新加载用户信息
                loadUserInfo();
                if (window.showMessage) {
                    window.showMessage('userMessage', '头像更新成功', true);
                } else {
                    alert('头像更新成功');
                }
            } else {
                if (window.showMessage) {
                    window.showMessage('userMessage', data.message || '头像更新失败', false);
                } else {
                    alert(data.message || '头像更新失败');
                }
            }
        })
        .catch(error => {
            console.error('头像上传失败:', error);
            if (window.showMessage) {
                window.showMessage('userMessage', '头像上传失败，请稍后重试', false);
            } else {
                alert('头像上传失败，请稍后重试');
            }
        });
    };
    reader.readAsDataURL(file);
}

// 显示修改用户信息模态框
window.showEditUserInfoModal = function() {
    if (!currentUserId) {
        alert('请先登录');
        return;
    }
    
    // 首先加载当前用户信息
    fetch(`/knowledge-qa/api/user/info/${currentUserId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success && data.user) {
                const user = data.user;
                
                // 创建修改用户信息的模态框
                let modalHTML = `
                    <div id="editUserInfoModal" class="modal" style="display:block;">
                        <div class="modal-content">
                            <span class="close" onclick="closeEditUserInfoModal()">&times;</span>
                            <h2>修改用户信息</h2>
                            <div id="editUserMessage" style="display:none" class="alert"></div>
                            <form id="editUserForm">
                                <div class="form-group">
                                    <label for="editNickname">昵称</label>
                                    <input type="text" id="editNickname" placeholder="请输入昵称" value="${user.nickname || ''}">
                                </div>
                                <div class="form-group">
                                    <label for="editIntroduction">个人简介</label>
                                    <textarea id="editIntroduction" placeholder="请输入个人简介" rows="4">${user.introduction || ''}</textarea>
                                </div>
                                <div class="form-group">
                                    <label for="editEmail">邮箱</label>
                                    <input type="email" id="editEmail" placeholder="请输入邮箱" value="${user.email || ''}">
                                </div>
                                <div class="form-group">
                                    <label for="editPhone">手机号</label>
                                    <input type="tel" id="editPhone" placeholder="请输入手机号" value="${user.phone || ''}">
                                </div>
                                <button type="button" class="btn btn-primary" onclick="submitUserInfoUpdate()">保存修改</button>
                            </form>
                        </div>
                    </div>
                `;
                
                // 检查模态框是否已存在，如果存在则移除
                const existingModal = document.getElementById('editUserInfoModal');
                if (existingModal) {
                    existingModal.remove();
                }
                
                // 添加模态框到body
                document.body.insertAdjacentHTML('beforeend', modalHTML);
            }
        })
        .catch(error => {
            console.error('加载用户信息失败:', error);
            alert('加载用户信息失败，请稍后重试');
        });
};

// 关闭修改用户信息模态框
window.closeEditUserInfoModal = function() {
    const modal = document.getElementById('editUserInfoModal');
    if (modal) {
        modal.remove();
    }
};

// 提交用户信息更新
function submitUserInfoUpdate() {
    const nickname = document.getElementById('editNickname').value;
    const introduction = document.getElementById('editIntroduction').value;
    const email = document.getElementById('editEmail').value;
    const phone = document.getElementById('editPhone').value;
    
    // 构建用户信息对象
    const userInfo = {
        id: currentUserId,
        nickname: nickname,
        introduction: introduction,
        email: email,
        phone: phone
    };
    
    // 发送更新请求
    fetch('/knowledge-qa/api/user/update', {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(userInfo)
    })
    .then(response => response.json())
    .then(data => {
        const messageElement = document.getElementById('editUserMessage');
        if (data.success) {
            // 更新成功，重新加载用户信息
            loadUserInfo();
            
            if (messageElement) {
                messageElement.textContent = '用户信息更新成功';
                messageElement.className = 'alert alert-success';
                messageElement.style.display = 'block';
            }
            
            // 2秒后关闭模态框
            setTimeout(() => {
                window.closeEditUserInfoModal();
            }, 2000);
        } else {
            if (messageElement) {
                messageElement.textContent = data.message || '用户信息更新失败';
                messageElement.className = 'alert alert-error';
                messageElement.style.display = 'block';
            }
        }
    })
    .catch(error => {
        console.error('更新用户信息失败:', error);
        const messageElement = document.getElementById('editUserMessage');
        if (messageElement) {
            messageElement.textContent = '更新失败，请稍后重试';
            messageElement.className = 'alert alert-error';
            messageElement.style.display = 'block';
        }
    });
}

// 加载交易记录
function loadTransactions(type) {
    const container = document.getElementById('transactionsContainer');
    container.innerHTML = '<p style="text-align:center; color:#999;">加载中...</p>';
    
    // 更新按钮样式
    document.getElementById('btnAllTransactions').className = 'btn';
    document.getElementById('btnRechargeRecords').className = 'btn';
    document.getElementById('btnConsumeRecords').className = 'btn';
    
    let url = '';
    switch (type) {
        case 'recharge':
            url = `/knowledge-qa/api/coin/recharge-records/${currentUserId}`;
            document.getElementById('btnRechargeRecords').className = 'btn btn-primary';
            break;
        case 'consume':
            url = `/knowledge-qa/api/coin/consume-records/${currentUserId}`;
            document.getElementById('btnConsumeRecords').className = 'btn btn-primary';
            break;
        default:
            url = `/knowledge-qa/api/coin/transactions/${currentUserId}`;
            document.getElementById('btnAllTransactions').className = 'btn btn-primary';
    }
    
    fetch(url)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const transactions = data.transactions || data.records || [];
                if (transactions.length === 0) {
                    container.innerHTML = '<p style="text-align:center; color:#999;">暂无交易记录</p>';
                    return;
                }
                
                let html = '<table class="transaction-table">';
                html += '<thead><tr><th>交易时间</th><th>类型</th><th>金额</th><th>备注</th></tr></thead>';
                html += '<tbody>';
                
                transactions.forEach(transaction => {
                    const typeText = getTransactionTypeText(transaction.type);
                    const amountClass = transaction.amount > 0 ? 'amount-positive' : 'amount-negative';
                    const amountText = transaction.amount > 0 ? '+' + transaction.amount : transaction.amount;
                    
                    html += `
                        <tr>
                            <td>${formatDate(transaction.createTime)}</td>
                            <td>${typeText}</td>
                            <td class="${amountClass}">${amountText}</td>
                            <td>${transaction.remark || '-'}</td>
                        </tr>
                    `;
                });
                
                html += '</tbody></table>';
                container.innerHTML = html;
            } else {
                container.innerHTML = '<p style="text-align:center; color:#ff4d4f;">加载失败</p>';
            }
        })
        .catch(error => {
            console.error('加载交易记录失败:', error);
            container.innerHTML = '<p style="text-align:center; color:#ff4d4f;">加载失败，请稍后重试</p>';
        });
}

// 获取交易类型文本
window.getTransactionTypeText = function(type) {
    switch (type) {
        case 0:
            return '充值';
        case 1:
            return '发布悬赏';
        case 2:
            return '打赏';
        case 3:
            return '其他';
        default:
            return '未知';
    }
}